{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Getting started with Interactive Brokers\n",
    "\n",
    "Our project connects to Interactive Brokers to perform trades.\n",
    "\n",
    "Interactive Brokers has two ways of accessing the API:\n",
    "* **TWS** - this is the main desktop client. It's useful for seeing what's going on and testing things. Shuts down automatically after 24 hours.\n",
    "* **Gateway** - this is a lightweight API client. It's still java based and requires a GUI login (there is no 'headless' API), but it's suitable for running a live system.\n",
    "\n",
    "There are also three levels of login:\n",
    "* Demo\n",
    "* Simulated/paper trading\n",
    "* Live trading\n",
    "\n",
    "These environments can quite different in behaviour (in terms of what instruments are available, and especially what historical/live data is available).\n",
    "\n",
    "## Using the demo Interactive Brokers mode to test API connectivity\n",
    "\n",
    "Download and install the latest TWS onto your computer.\n",
    "\n",
    "Open it and log in with:\n",
    "* Username: edemo\n",
    "* Password: demouser\n",
    "\n",
    "Go into the settings and configure the API:\n",
    "* Enable the API on port 4003\n",
    "* Disable Read-only API\n",
    "\n",
    "Our system has a module at core.ibstate which handles the connection to IB. IB's API is realtime & event driven.\n",
    "\n",
    "The following code should connect to IB:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-06-16T12:39:33.826949+01:00",
     "start_time": "2017-06-16T12:39:23.175952"
    },
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "import os\n",
    "os.chdir('..')\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import trading.start\n",
    "import trading.portfolio as portfolio\n",
    "import config.settings\n",
    "from time import sleep\n",
    "from core.utility import *\n",
    "from trading.accountcurve import *\n",
    "import data.db_mongo as db\n",
    "import config.portfolios\n",
    "from pylab import rcParams\n",
    "rcParams['figure.figsize'] = 15, 10\n",
    "p = portfolio.Portfolio(instruments=config.portfolios.p_trade)\n",
    "i = p.instruments\n",
    "from trading.ibstate import *\n",
    "\n",
    "ib = IBstate()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "IB has recently introduced a Python API, but we don't use it yet (we currently use IbPy, which is a Python module that maps to the Java API https://github.com/blampe/IbPy). \n",
    "\n",
    "The official API docs are here:\n",
    "http://interactivebrokers.github.io/tws-api/\n",
    "\n",
    "The API consists of two main components:\n",
    "* Client\n",
    "* Wrapper\n",
    "\n",
    "We send instructions to the API with the Client, and receive responses back via Wrapper. We have to subscribe to various event streams to receive responses from the API. IBstate tries to collect all these realtime responses to maintain a 'stateful' respresentation of what is going on. For example, our account balance ('net liquidiation') will change throughout the day. IBstate listens for these updates and remembers them, so when we call:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ib.net()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "it returns a result from our local buffer.\n",
    "\n",
    "IBstate can also collect responses and join them together (for example, portfolios are returned line by line, IBstate joins them together into a Pandas dataframe, so we can work it more easily).\n",
    "\n",
    "IBState also allows us to trade. The magic command is:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ib.sync_portfolio(p, trade = True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When you run this, you should start to see the trades go into TWS. It pauses for 60 seconds between each trade, so this will take several minutes to run.\n",
    "\n",
    "If you refresh the following command, you should see a mirror image of what you see in the TWS interface."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "ib.portfolio"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [conda root]",
   "language": "python",
   "name": "conda-root-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
